/**
 * Copyright (c) 2016-2019 人人开源 All rights reserved.
 * <p>
 * https://www.renren.io
 * <p>
 * 版权所有，侵权必究！
 */

package io.renren.modules.sys.service.impl;


import cn.hutool.core.collection.CollectionUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import io.renren.common.utils.Constant;
import io.renren.common.utils.PageUtils;
import io.renren.common.utils.Query;
import io.renren.modules.dangan.service.DaUserFlhService;
import io.renren.modules.dangan.service.DaUserLocationService;
import io.renren.modules.sys.dao.SysUserDao;
import io.renren.modules.sys.entity.SysDeptEntity;
import io.renren.modules.sys.entity.SysRoleEntity;
import io.renren.modules.sys.entity.SysUserEntity;
import io.renren.modules.sys.service.SysDeptService;
import io.renren.modules.sys.service.SysRoleService;
import io.renren.modules.sys.service.SysUserRoleService;
import io.renren.modules.sys.service.SysUserService;
import io.renren.modules.sys.shiro.ShiroUtils;
import org.apache.commons.lang.RandomStringUtils;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;


/**
 * 系统用户
 *
 * @author Mark sunlightcs@gmail.com
 */
@Service("sysUserService")
public class SysUserServiceImpl extends ServiceImpl<SysUserDao, SysUserEntity> implements SysUserService {
    @Autowired
    private SysUserRoleService sysUserRoleService;
    @Autowired
    private SysDeptService sysDeptService;

    @Autowired
    private SysRoleService sysRoleService;

    @Autowired
    private DaUserLocationService daUserLocationService;

    @Autowired
    private DaUserFlhService daUserFlhService;
    @Override
    public List<Long> queryAllMenuId(Long userId) {
        return baseMapper.queryAllMenuId(userId);
    }

    @Override
    public PageInfo queryDetail(Map<String, Object> params) {
        String username = (String) params.get("username");
        Long deptId = Long.parseLong(params.getOrDefault("deptId", new Long(0)).toString());
        PageHelper.startPage(Integer.parseInt((String) params.getOrDefault(Constant.PAGE, "1")),
                Integer.parseInt((String) params.getOrDefault(Constant.LIMIT, "10")));
        List<SysUserEntity> userEntities = baseMapper.findUserDetailByDeptId(deptId);
        userEntities.forEach(user -> {
            if (CollectionUtil.isNotEmpty(user.getRoleIds())) {
                user.getRoleIds().forEach(roleId -> {
                    SysRoleEntity roleEntity = sysRoleService.findRoleDetailById(roleId);
                    if (CollectionUtil.isNotEmpty(roleEntity.getFlhs())) {
                        user.getFlhs().addAll(roleEntity.getFlhs());
                    }
                    if (CollectionUtil.isNotEmpty(roleEntity.getSzds())) {
                        user.getSzds().addAll(roleEntity.getSzds());
                    }
					user.getRoles().add(roleEntity);
				});
                //去重
                HashSet flhSet=new HashSet(user.getFlhs());
                ArrayList flhs=new ArrayList();
                flhs.addAll(flhSet);
                user.setFlhs(flhs);
                HashSet szdSet=new HashSet(user.getSzds());
                ArrayList szds=new ArrayList();
                szds.addAll(szdSet);
                user.setSzds(szds);
            }

        });
        return new PageInfo(userEntities);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void saveRoleFlhSzd(List<String> locations, List<String> flhs, int userId, List<Long> roleIds) {
        HashSet<String> flhSet = new HashSet<>();
        HashSet<String> szdSet = new HashSet<>();
        if(CollectionUtil.isNotEmpty(locations)){
        	szdSet.addAll(locations);
		}
        if(CollectionUtil.isNotEmpty(flhs)){
        	flhs.addAll(flhs);
		}

        if (CollectionUtil.isNotEmpty(roleIds)) {
            roleIds.forEach(roleId -> {
                SysRoleEntity roleEntity = sysRoleService.findRoleDetailById(roleId);
                flhSet.addAll(roleEntity.getFlhs());
                szdSet.addAll(roleEntity.getSzds());
            });
        }
        sysUserRoleService.saveOrUpdate(new Long(userId),roleIds);
        flhs=new ArrayList<>(flhSet);
        locations=new ArrayList<>(szdSet);
        if(CollectionUtil.isNotEmpty(flhs)){
            daUserFlhService.saveBatch(userId,flhs);
        }
        if(CollectionUtil.isNotEmpty(locations)){
            daUserLocationService.saveBatch(userId,locations);
        }
    }

    @Override
//	@DataFilter(subDept = true, user = false)
    public PageUtils queryPage(Map<String, Object> params) {
        String username = (String) params.get("username");
        String ssoLoginName= (String) params.get("ssoLoginName");
        IPage<SysUserEntity> page = this.page(
                new Query<SysUserEntity>().getPage(params),
                new QueryWrapper<SysUserEntity>()
                        .like(StringUtils.isNotBlank(username), "username", username)
                        .eq(StringUtils.isNotBlank(ssoLoginName),"sso_login_name",ssoLoginName)
                        .apply(params.get(Constant.SQL_FILTER) != null, (String) params.get(Constant.SQL_FILTER))
        );

        for (SysUserEntity sysUserEntity : page.getRecords()) {
            SysDeptEntity sysDeptEntity = sysDeptService.getById(sysUserEntity.getDeptId());
            sysUserEntity.setDeptName(sysDeptEntity.getName());
        }

        return new PageUtils(page);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void saveUser(SysUserEntity user) {
        user.setCreateTime(new Date());
        //sha256加密
        String salt = RandomStringUtils.randomAlphanumeric(20);
        user.setSalt(salt);
        user.setPassword(ShiroUtils.sha256(user.getPassword(), user.getSalt()));
        this.save(user);

        //保存用户与角色关系
        sysUserRoleService.saveOrUpdate(user.getUserId(), user.getRoleIdList());
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void update(SysUserEntity user) {
        if (StringUtils.isBlank(user.getPassword())) {
            user.setPassword(null);
        } else {
            SysUserEntity userEntity = this.getById(user.getUserId());
            user.setPassword(ShiroUtils.sha256(user.getPassword(), userEntity.getSalt()));
        }
        this.updateById(user);

        //保存用户与角色关系
        sysUserRoleService.saveOrUpdate(user.getUserId(), user.getRoleIdList());
    }


    @Override
    public boolean updatePassword(Long userId, String password, String newPassword) {
        SysUserEntity userEntity = new SysUserEntity();
        userEntity.setPassword(newPassword);
        userEntity.setHasResetPwd(1);
        return this.update(userEntity,
                new QueryWrapper<SysUserEntity>().eq("user_id", userId).eq("password", password));
    }

    @Override
    public boolean resetPassword(Long userId, String newPassword) {
        SysUserEntity userEntity = new SysUserEntity();
        userEntity.setPassword(newPassword);
        userEntity.setHasResetPwd(0);
        return this.update(userEntity,
                new QueryWrapper<SysUserEntity>().eq("user_id", userId));
    }

    @Override
    public boolean deleteByDeptId(long deptId) {
        try{
            this.remove(new QueryWrapper<SysUserEntity>().eq("dept_id",deptId));
        }catch (Exception e){
            return false;
        }
        return true;
    }


}
